import { FileStorage, BaseModel } from '../utils/fileStorage';
import path from 'path';

export interface ConfigData extends BaseModel {
  nginxExec?: string;
  nginxCwd?: string;
  nginxConfDir?: string;
  isDockerized?: boolean;
  dockerContainerName?: string;
  dockerHostPath?: string;
  dockerContainerPath?: string;
  dockerHostLogPath?: string;
  dockerContainerLogPath?: string;
  dockerHostSslPath?: string;
  dockerContainerSslPath?: string;
}


export class ConfigModel {
  private static storage = new FileStorage<ConfigData>('config.json');

  // 创建配置记录
  static async create(data: Omit<ConfigData, 'id' | 'createdAt' | 'updatedAt'>): Promise<number> {
    return this.storage.create(data);
  }

  // 获取配置记录
  static async findById(id: number): Promise<ConfigData | null> {
    return this.storage.findById(id) || null;
  }

  // 获取所有配置记录
  static async findAll(): Promise<ConfigData[]> {
    return this.storage.findAll();
  }

  // 更新配置记录
  static async update(id: number, data: Partial<ConfigData>): Promise<void> {
    this.storage.update(id, data);
    return;
  }

  // 删除配置记录
  static async delete(id: number): Promise<void> {
    this.storage.delete(id);
    return;
  }

  // 获取系统配置
  static async getSystemConfig(): Promise<ConfigData> {
    try {
      const config = this.storage.findById(1);
      if(config) {
        return config;
      }
      return Promise.resolve({
        nginxExec: '/usr/sbin/nginx',
        nginxCwd: '/etc/nginx',
        nginxConfDir: '/etc/nginx/conf.d',
        isDockerized: false,
        dockerHostSslPath: '/etc/nginx/ssl',
        dockerContainerSslPath: '/etc/nginx/ssl'
      });
    } catch (error) {
      // 如果配置文件不存在，返回默认配置
      return Promise.resolve({
        nginxExec: '/usr/sbin/nginx',
        nginxCwd: '/etc/nginx',
        nginxConfDir: '/etc/nginx/conf.d',
        isDockerized: false,
        dockerHostSslPath: '/etc/nginx/ssl',
        dockerContainerSslPath: '/etc/nginx/ssl'
      });
    }
  }

  // 更新系统配置
  static async updateSystemConfig(config: ConfigData): Promise<void> {
    this.storage.update(1, config);
  }

  // 创建系统配置
  static async createSystemConfig(config: Partial<ConfigData>): Promise<void> {
    const currentConfig = await this.getSystemConfig();
    const newConfig = { ...currentConfig, ...config };
    await this.updateSystemConfig(newConfig);
  }
}